import axios from 'axios';
import {
  Message, MessageBox
} from 'element-ui';
import store from '../store';
import {
  getToken
} from 'utils/auth';

// 创建axios实例
const service = axios.create({
	baseURL: '', // api的base_url
//	baseURL: '/api',
  timeout: 5000 // 请求超时时间
});

// request拦截器
service.interceptors.request.use(config => {
  // Do something before request is sent
  if(localStorage.getItem('access-token')){
    config.headers['access-token'] = localStorage.getItem('access-token') // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
//	config.headers['Admin-token'] = getToken();
	}
	if(config.data){
		var dateRegex = /^(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)$/;
		if(config.data.startDate && !dateRegex.test(config.data.startDate)){
			config.data.startDate = (config.data.startDate).Format("yyyy-MM-dd")
		}
		if(config.data.endDate && !dateRegex.test(config.data.endDate)){
			config.data.endDate = (config.data.endDate).Format("yyyy-MM-dd")
		}
		if(config.data.date && !dateRegex.test(config.data.date)){
			config.data.date = (config.data.date).Format("yyyy-MM-dd")
		}
		if(config.data.shutDownDate && !dateRegex.test(config.data.shutDownDate)){
			config.data.shutDownDate = (config.data.shutDownDate).Format("yyyy-MM-dd") 
		}
		if(config.data.launchDate && !dateRegex.test(config.data.launchDate)){
			config.data.launchDate = (config.data.launchDate).Format("yyyy-MM-dd")
		}
		if(config.data.addedDate && !dateRegex.test(config.data.addedDate)){
			config.data.addedDate = (config.data.addedDate).Format("yyyy-MM-dd")
		}
	}
  return config;
}, error => {
  // Do something with request error
  console.log(error); // for debug
  Promise.reject(error);
})

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */
     const res = response.data;
    if (response.status == 401 || res.status == 401 || res.status == 403) {
   	  // location.href = 'localhost/login';
    	console.log('token失效，返回到登录页');
    	localStorage.removeItem('access-token');
      this.$router.push({ name: '登录', }).then(() => {
      		localStorage.removeItem('access-token')
         	location.reload(); // 为了重新实例化vue-router对象 避免bug
      });
      return Promise.reject('error');
    }
    if (response.status !== 200 && res.status !== 200) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      });
    } else {
      return response.data;
    }
  },
  error => {
    console.log('err' + error); // for debug
		let errMsg;
		let timeMsg;
    if(localStorage.getItem('locale') === 'zh_cn'){
    	 errMsg = '请稍候再试';
    	 timeMsg = '闲置时间过长，请重新登录';
    }else if(localStorage.getItem('locale') === 'zh_tw'){
    	 errMsg = '請稍後再試';
    	 timeMsg = '閒置時間過長，請重新登入';
    }else{
    	 errMsg = 'Please try again later';
    	 timeMsg = 'Idle for too long, please re-login';
    }
    if(error.message === 'Request failed with status code 500'){
					Message({ message: errMsg + '   100500' , duration: 5 * 1000 })
		}else if(error.message === 'Request failed with status code 504'){
		    	Message({ message: errMsg + '   100504' , duration: 5 * 1000 })  
		}else if(error.message === 'timeout of 5000ms exceeded'){
		    	Message({ message: errMsg + '   100100' , duration: 5 * 1000 });
		}else if(error.message === 'Request failed with status code 401'){
					localStorage.removeItem('access-token');
					localStorage.removeItem('access-userId');
					localStorage.removeItem('companyId');
					localStorage.removeItem('distributorId');
		    	Message({ message: timeMsg, duration: 5 * 1000 });
					this.$router.push({ name: '登录', }).then(() => {
						 location.reload(); // 为了重新实例化vue-router对象 避免bug
					});
		}
    return Promise.reject(error);
  }
);

export default service;
